/*
 * hkh-project
 * leafteamwork.blogspot.com
 * Tool: Netbeans 6.7.1 - SQL Server 2005
 */
package vn.com.hkh.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author leaf
 */
public class DatabaseUtil {

    private static Logger logger = Logger.getLogger(DatabaseUtil.class.getName());

    /**
     * Get a database connection
     * @return Connection
     */
    public static Connection getConnection() {
        Connection con = null;
        String driver = DatabaseConfig.readKey("jdbcdriver");
        String sqlURL = DatabaseConfig.readKey("jdbcurl");
        String sqlUser = DatabaseConfig.readKey("jdbcusername");
        String sqlPassword = DatabaseConfig.readKey("jdbcpassword");
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(sqlURL, sqlUser, sqlPassword);
            return con;
        } catch (ClassNotFoundException ex) {
            logger.log(Level.SEVERE, null, ex);
            return null;
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Close a database connection
     * @param con the database connection
     */
    public static void closeConnection(Connection con) {
        try {
            if (!con.isClosed()) {
                con.close();
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Generate Id
     * @return String
     */
    public static String generateUUID() {
        UUID uudi = UUID.randomUUID();
        return String.valueOf(uudi);
    }

    /**
     * Generate md5 string
     * @param str
     * @return String
     */
    public static String generateMD5(String str) {
        String hashword = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            BigInteger hash = new BigInteger(1, md5.digest());
            hashword = hash.toString(16);
        } catch (NoSuchAlgorithmException nsae) {
            logger.log(Level.SEVERE, null, nsae);
        }
        return hashword;
    }

    public static String getYMD(String dmy)
    {
        String yMD = "";
        String[] temps = dmy.split("/");
        yMD = temps[2] + "-" + temps[1] + "-" + temps[0];
        return yMD;
    }
}
